<template>
  <div v-if="permission||$route.path.includes('/publicReport')"
       class="dashboard-page report_layout absolute inset-0 flex flex-col"
     
       style="width:100%;bottom:auto">
    <span class="btnBox"
          @click="showDesign"
          v-if="hasEditPermission&& !showMsg&&$hasPermission('sys:report:reportadmin')">
      <i class="el-icon-more showBtn"></i>
    </span>
    <div class="top-toolbar"
         v-if="showMsg&&$hasPermission('sys:report:reportadmin')">
      <div class="top-toolbar-title"></div>
      <div class="top-toolbar-tool">
        <el-button-group style="position:absolute;right:40px;top:6px;">
          <el-button style="height: 24px;padding: 5px 15px;"
                     icon="el-icon-plus"
                     v-if="editMode && hasEditPermission"
                     size="mini"
                     type="success"
                     v-on:click.native='selectedgadgetPop'>{{ $t('add') }}
          </el-button>
          <el-button size="mini"
                     type="primary"
                     style="height: 24px;padding: 5px 15px;"
                     v-if="hasEditPermission"
                     icon="el-icon-edit"
                     v-on:click.native='toggleClick'
                     ref="toggleBtn">{{ editMode ? 'Save' : 'Design' }}
          </el-button>
          <!-- MB-4780 start -->
          <el-button size="mini"
                     style="height: 24px;padding: 5px 15px;"
                     v-if="$hasPermission('sys:tenant:model:allowtomanage:report:temmodel')&&false"
                     icon="el-icon-document-copy">{{ $t('custom.reports.clonebtn') }}
          </el-button>
          <el-button size="mini"
                     v-if="$hasPermission('sys:tenant:model:allowtomanage:report:temmodel')&&false"
                     icon="el-icon-printer">{{ $t('custom.reports.botbtn') }}
          </el-button>
          <!-- <el-button size="mini"
                     type="primary"
                     style="height: 24px;padding: 5px 15px;"
                     icon="el-icon-edit">
            Design
          </el-button> -->
          <!-- MB-4780 end -->
        </el-button-group>
        <i class="el-icon-circle-close closeBtn"
           @click="closeDesign"></i>
      </div>
    </div>
    <div v-loading="loading"
         style="min-height:calc(100vh - 120px)">
      <div>
        <grid-layout :layout.sync="gadgets"
                     v-if="!isShow"
                     :col-num="12"
                     :row-height="10"
                     :margin="[12,12]"
                     :is-draggable="dashbordDefaultSetting.allowDragging"
                     :is-resizable="dashbordDefaultSetting.allowResizing"
                     :vertical-compact="true"
                     responsive
                     :use-css-transforms="true">
          <grid-item v-for="(item,index) in gadgets"
                     :data-gadgetType="+isSlicer(item.com)"
                     :class="{'auto_class':item.com === 'homepagegadget'||item.com==='newstepgadget'}"
                     :x="item.x"
                     :y="item.y"
                     :w="item.w"
                     :h="item.h <2?2:item.h"
                     :i="item.i"
                     :key="item.i"
                     :static="item.static"
                     @resized="resizedEvent"
                     @mouseenter.native="mouseEnterModule(index)"
                     @mouseleave.native="mouseLeaveModule(index)">
            <!-- &&item&&item.showSetting&&item.showSetting === 'show' -->
            <div class="widget_div"
                 style="width:100;height:100%">

              <div v-if="editMode"
                   class="flex flex-col items-center widget_div_item"
                   :style="isSlicer(item.com)?'width:20px;position:absolute;top:-50px;right:30px;z-index:2020;transform:rotate(-90deg);border-left:1px solid #f1f4f5':'width:20px;position:absolute;top:4px;right:-22px;z-index:2020;border-left:1px solid #f1f4f5'">
                <i @mouseenter="moveComponent(true)"
                   @mouseleave="moveComponent(false)"
                   :title="$t('custom.move')"
                   class="el-icon-rank"
                   v-if="!(item.com==='pageheadergadget')"
                   style="cursor:pointer;display:inline-block;backgroundColor:#fff;padding:5px"></i>
                <!-- v-if="$hasPermission('sys:tenant:model:allowtomanage:report:temmodel')" -->
                <i v-if="hasPageHeaderPer(item.com)"
                   @click="editComponent(item.i,item)"
                   :title="$t('custom.edit')"
                   class="cuifont icon_edit"
                   style="cursor:pointer;display:inline-block;backgroundColor:#fff;padding:5px;margin-top:5px;font-size:14px"></i>
                <i @click="closeComponent(item.i)"
                   :title="$t('custom.remove')"
                   v-if="!(item.com==='pageheadergadget')"
                   class="cuifont icon_delete"
                   :style="isSlicer(item.com)?'cursor:pointer;display:inline-block;backgroundColor:#fff;padding:5px;margin-top:5px;font-size:14px;transform:rotate(90deg);':'cursor:pointer;display:inline-block;backgroundColor:#fff;padding:5px;margin-top:5px;font-size:14px'"></i>
              </div>
              <component :editMode='editMode'
                         style="width:100%;height:calc(100% - 32px)"
                         :gadgetInfo='item'
                         @dragChanged='gadgetDragChanged'
                         ref="gadgets"
                         @removed='gadgetRemoved'
                         :id='item.i'
                         :name="item.name"
                         :pageId='pageId'
                         :fitToHeight.sync="fitToHeight"
                         :zoomNumber="zoomNumber"
                         :presentMode="true"
                         :businessType='businessTypeForWidget'
                         :reportNameForPage='reportNameForPage'
                         :is="item.com"></component>
            </div>
          </grid-item>
          <div v-if="gadgets.length === 1"
               style="display: flex;justify-content: center ;align-items:center ;height: 80vh;background: #fff; margin-top:10px;">
            <img :src="$ossLink+'/app/dashboard/dashboard-left.png'"
                 style="height:500px" />
            <div style="margin-left:120px;">
              <div style="font-size: 34px;margin-bottom: 10px;">{{ $t('custom.dashboard.nulldatafirst') }}</div>
              <div style="font-size: 34px;margin-bottom: 15px;">{{ $t('custom.dashboard.nulldatasecond') }}</div>
              <div style="font-size: 20px;margin-bottom: 20px;color: #c8c8c8;">{{ $t('custom.dashboard.nulldatathree') }}
              </div>
              <div>
                <el-button type="success"
                           v-if="hasEditPermission"
                           @click="addgauge">{{ $t('custom.reports.nullwidget') }}
                </el-button>
              </div>
            </div>
          </div>
        </grid-layout>
        <div v-else>
          <grid-layout :layout.sync="gadgets1"
                       :col-num="12"
                       :row-height="10"
                       :margin="[12,12]"
                       :is-draggable="dashbordDefaultSetting.allowDragging"
                       :is-resizable="dashbordDefaultSetting.allowResizing"
                       :vertical-compact="true"
                       responsive
                        class="widget-page-header"
                       :use-css-transforms="true">
            <grid-item v-for="(item,index) in gadgets1"
                       :data-gadgetType="+isSlicer(item.com)"
                       :class="{'auto_class':item.com === 'homepagegadget'||item.com==='newstepgadget'}"
                       :x="item.x"
                       :y="item.y"
                       :w="item.w"
                       :h="item.h <2?2:item.h"
                       :i="item.i"
                       :key="item.i"
                       :static="item.static"
                       @resized="resizedEvent"
                       @mouseenter.native="mouseEnterModule(index)"
                       @mouseleave.native="mouseLeaveModule(index)">
              <!-- &&item&&item.showSetting&&item.showSetting === 'show' -->
              <div class="widget_div"
                   style="width:100;height:100%">

                <div v-if="editMode"
                     class="flex flex-col items-center widget_div_item"
                     :style="isSlicer(item.com)?'width:20px;position:absolute;top:-50px;right:30px;z-index:2020;transform:rotate(-90deg);border-left:1px solid #f1f4f5':'width:20px;position:absolute;top:4px;right:-22px;z-index:2020;border-left:1px solid #f1f4f5'">
                  <i @mouseenter="moveComponent(true)"
                     @mouseleave="moveComponent(false)"
                     :title="$t('custom.move')"
                     class="el-icon-rank"
                     v-if="!(item.com==='pageheadergadget')"
                     style="cursor:pointer;display:inline-block;backgroundColor:#fff;padding:5px"></i>
                  <!-- v-if="$hasPermission('sys:tenant:model:allowtomanage:report:temmodel')" -->
                  <i v-if="hasPageHeaderPer(item.com)"
                     @click="editComponent(item.i,item)"
                     :title="$t('custom.edit')"
                     class="cuifont icon_edit"
                     style="cursor:pointer;display:inline-block;backgroundColor:#fff;padding:5px;margin-top:5px;font-size:14px"></i>
                  <i @click="closeComponent(item.i)"
                     :title="$t('custom.remove')"
                     v-if="!(item.com==='pageheadergadget')"
                     class="cuifont icon_delete"
                     :style="isSlicer(item.com)?'cursor:pointer;display:inline-block;backgroundColor:#fff;padding:5px;margin-top:5px;font-size:14px;transform:rotate(90deg);':'cursor:pointer;display:inline-block;backgroundColor:#fff;padding:5px;margin-top:5px;font-size:14px'"></i>
                </div>
                <component :editMode='editMode'
                           style="width:100%;height:calc(100% - 32px)"
                           :gadgetInfo='item'
                           @dragChanged='gadgetDragChanged'
                           ref="gadgets"
                           @removed='gadgetRemoved'
                           :id='item.i'
                           :name="item.name"
                           :pageId='pageId'
                           :fitToHeight.sync="fitToHeight"
                           :zoomNumber="zoomNumber"
                           :presentMode="true"
                           :businessType='businessTypeForWidget'
                           :reportNameForPage='reportNameForPage'
                           :is="item.com"></component>
              </div>
            </grid-item>
          </grid-layout>
          <grid-layout :layout.sync="gadgets2"
                       :class="`vue_grid_layout_${this.pageId}`"
                       :col-num="12"
                       :row-height="10"
                       responsive
                       :margin="[12,12]"
                       style="margin-top: -20px;"
                       :is-draggable="dashbordDefaultSetting.allowDragging"
                       :is-resizable="dashbordDefaultSetting.allowResizing"
                       :vertical-compact="true"
                       :use-css-transforms="true">
            <grid-item v-for="(item,index) in gadgets2"
                       :data-gadgetType="+isSlicer(item.com)"
                       :class="{'auto_class':item.com === 'homepagegadget'||item.com==='newstepgadget'}"
                       :x="item.x"
                       :y="item.y"
                       :w="item.w<1?1:item.w"
                       :h="item.h <2?2:item.h"
                       :i="item.i"
                       :key="item.i"
                       :static="item.static"
                       @resized="resizedEvent"
                       @mouseenter.native="mouseEnterModule(index)"
                       @mouseleave.native="mouseLeaveModule(index)"
                       class="widget-card-border">
              <!-- &&item&&item.showSetting&&item.showSetting === 'show' -->
              <div class="widget_div"
                   style="width:100;height:100%">

                <div v-if="editMode"
                     class="flex flex-col items-center widget_div_item"
                     :style="isSlicer(item.com)?'width:20px;position:absolute;top:-50px;right:30px;z-index:2020;transform:rotate(-90deg);border-left:1px solid #f1f4f5':'width:20px;position:absolute;top:4px;right:-22px;z-index:2020;border-left:1px solid #f1f4f5'">
                  <i @mouseenter="moveComponent(true)"
                     @mouseleave="moveComponent(false)"
                     :title="$t('custom.move')"
                     class="el-icon-rank"
                     v-if="!(item.com==='pageheadergadget')"
                     style="cursor:pointer;display:inline-block;backgroundColor:#fff;padding:5px"></i>
                  <!-- v-if="$hasPermission('sys:tenant:model:allowtomanage:report:temmodel')" -->
                  <i v-if="hasPageHeaderPer(item.com)"
                     @click="editComponent(item.i,item)"
                     :title="$t('custom.edit')"
                     class="cuifont icon_edit"
                     style="cursor:pointer;display:inline-block;backgroundColor:#fff;padding:5px;margin-top:5px;font-size:14px"></i>
                  <i @click="closeComponent(item.i)"
                     :title="$t('custom.remove')"
                     v-if="!(item.com==='pageheadergadget')"
                     class="cuifont icon_delete"
                     :style="isSlicer(item.com)?'cursor:pointer;display:inline-block;backgroundColor:#fff;padding:5px;margin-top:5px;font-size:14px;transform:rotate(90deg);':'cursor:pointer;display:inline-block;backgroundColor:#fff;padding:5px;margin-top:5px;font-size:14px'"></i>
                </div>
                <component :editMode='editMode'
                           :style="{'width':'100%','height':(item.com === 'formviewdatagadget'||item.com === 'htmleditorgadget')?'100%':'calc(100% - 32px)'}"
                           :gadgetInfo='item'
                           @dragChanged='gadgetDragChanged'
                           ref="gadgets"
                           @removed='gadgetRemoved'
                           @fullScreen="fullScreen"
                           :id='item.i'
                           :name="item.name"
                           :pageId='pageId'
                           :fitToHeight.sync="fitToHeight"
                           :zoomNumber="zoomNumber"
                           :presentMode="true"
                           :comPageWidth="comPageWidth"
                           :businessType='businessTypeForWidget'
                           :reportNameForPage='reportNameForPage'
                           :pageFrom="'reportLayout'"
                           :is="item.com"></component>
              </div>
            </grid-item>
            <div v-if="gadgets.length === 1"
                 style="display: flex;justify-content: center ;align-items:center ;height: 82vh;background: #fff; margin:10px 10px 0">
              <img :src="$ossLink+'/app/dashboard/dashboard-left.png'"
                   style="height:500px" />
              <div style="margin-left:120px;">
                <div style="font-size: 34px;margin-bottom: 10px;">{{ $t('custom.dashboard.nulldatafirst') }}</div>
                <div style="font-size: 34px;margin-bottom: 15px;">{{ $t('custom.dashboard.nulldatasecond') }}</div>
                <div style="font-size: 20px;margin-bottom: 20px;color: #c8c8c8;">{{ $t('custom.dashboard.nulldatathree') }}
                </div>
                <div>
                  <el-button type="success"
                             v-if="hasEditPermission"
                             @click="addgauge">{{ $t('custom.reports.nullwidget') }}
                  </el-button>
                </div>
              </div>
            </div>
          </grid-layout>
        </div>
      </div>

      <ZScreenHu v-if="curTheme && curTheme !=='white'"/>
      <model :showSetting="queryModelDefaultSetting.showSetting"
             @queryModelClosed="queryModelClosed"
             ref="model"
             @refreshDataList="refreshDataList"
             :dataInfo="queryModelDefaultSetting.dataInfo"
             :updateGadget="updateGadget"
             :mappingForm="mappingForm" />
    </div>
    <InterGetStarted :integrationCode="reportIntegrationCode"
                     ref="inter-get-started-dialog" />
    <nextTicketConnectTip :integrationCode="reportIntegrationCode"
                          :nextTicket="nextTicketFrom"
                          ref="nextTicketConnectTipDialog" />
    <div ref="dashboard-page-tag"
         style="display:none;"></div>
    <homePageConnectTip :seeDialog="this.$store.state.user.integrationEventType" />

    <el-dialog width="90vw"
               :visible.sync="dialog"
               @closed="clearFormData"
               title="Select Dashboard">
      <ComplexWidgetForm v-if="dialog" />
    </el-dialog>

    <BDashboardAddWidget v-model="gadgets"
                         :internalWidget="businessTypeForWidget === 'MSPbots Internal'"
                         :internalSlicer="businessTypeForWidget === 'MSPbots Internal'"
                         :widget="businessTypeForWidget !== 'MSPbots Internal'"
                         :slicer="businessTypeForWidget !== 'MSPbots Internal'"
                         :rootBusinessType="businessTypeForWidget"
                         :visible.sync="gadgetChoiceModalVisible"
                         @event:open-widget-modal="selectGadget" />
    <ShareLinkDialog ref="share-link"
                     source="dashboard"
                     resourceType="ReportHeader" />
    <div class="fullScreenDialog"
         v-if="isFullScreen">
      <component :editMode='editMode'
                 style="width:100%;height:100%"
                 :gadgetInfo='fullScreenData'
                 @dragChanged='gadgetDragChanged'
                 @removed='gadgetRemoved'
                 @fullScreen="fullScreen"
                 :id='fullScreenData.i'
                 :name="fullScreenData.name"
                 :pageFrom="'reportLayoutFullScreen'"
                 :pageId='pageId'
                 :presentMode="false"
                 :businessType='businessTypeForWidget'
                 :reportNameForPage='reportNameForPage'
                 :is="fullScreenData.com" />
    </div>
    <div class="blueTheme"></div>
  </div>

  <div class="absolute inset-0 flex flex-col"
       v-loading="authLoading"
       v-else>
    <ZContainer>
      <ZEmpty description="No Permission"
              v-if="!authLoading" />
    </ZContainer>
  </div>

</template>

<script>
import mixinDashboardViewModule from '@/mixins/dashboard-view-module'
import mixinViewModule from '@/mixins/crud-view-module'
import { dashboardGadgetList, defaultGadgetSettingList } from '@/utils/data-json'
import model from '@/components/gadget/query-model/query-model.vue'
import nextTicketConnectTip from './nextTicketConnectTip'
import homePageConnectTip from '@/components/homePageConnectTip/homePageConnectTip.vue'
import ComplexWidgetForm from './components/complex-widget-form'
import EmitterMixin from '@/mixins/emitter'
import { getUUID } from '@/utils'
// import { getNextAppInfo } from '@/utils/common'

import ZContainer from '@/components/storybook/z-container'
import ZEmpty from '@/components/storybook/z-empty'
import { getGadget } from '@/components/storybook/hooks/useGadget'
import ZScreenHu from '@/components/storybook/z-screen-hu'
import bus from '@/components/storybook/utilties/bus'

// import config from '@/utils/config'
export default {
  name: 'ReportLayout',
  mixins: [mixinDashboardViewModule, mixinViewModule, EmitterMixin],
  provide () {
    return {
      getBusinessTypeForWidget: () => this.businessTypeForWidget,
      componentName: 'ReportLayout',
      editMode: () => this.editMode
    }
  },
  inject: ['refresh'],
  // props: ['nextTicketType'],
  components: {
    model,
    nextTicketConnectTip,
    ComplexWidgetForm,
    homePageConnectTip,
    ZScreenHu,
    ZContainer,
    ZEmpty
  },
  data () {
    return {
      reportRelationIntrogrationList: [],
      mixinViewModuleOptions: {
        createdIsNeed: false
      },
      nextTicketFrom: 'emty',
      titleTabs: 'title',
      currentPage: 1,
      checkedGauge: [],
      dataForm: {
        dataset: ''
      },
      searchVal: '',
      checkedCities: [],
      businessTypeListrecord: [],
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: '',
          gadgetId: '',
          gadgetType: '',
          gadgetSetting: {},
          reuse: true
        }
      },
      widgets: [],
      zoomNumber: 1,
      fitToHeight: false,
      needCheck: true
    }
  },
  activated () {
    this.$on('event:bind-widget', this.bindWidget)
    this.$on('event:open-gadget', this.selectGadget)
    this.$on('event:preview-widget', this.PreviewWidget)
    this.$root.eventBus.$on('updateTemplateId', (id, data) => {
      var res = this.gadgets.find(item => item.id === id)
      if (res) {
        res.id = data.id
        res.businessType = 'Custom'
        res.i = data.gadgetId
        this.toggleClick()
      }
    })
    this.$root.eventBus.$on('closeDialog', () => {
      this.dialog = false
      this.dialogOptions = false
    })
    this.$root.eventBus.$on('gadgetLoadingStatusCheck', () => {
      this.gadgetLoadingStatusCheck()
    })
    this.$root.eventBus.$on('event:updateGadgets', (data) => {
      this.gadgets = data || []
    })
    bus.$on('Dashboards-Share', (data, type) => {
      if (data) {
        let url = `${window.location.origin}/publicReport?pageid=${this.dashboardsDetailsData.businessId}&name=${this.dashboardsDetailsData.name}`
        this.$nextTick(() => {
          this.$refs['share-link'].init(this.dashboardsDetailsData, url, type)
        })
      }
    })
  },
  deactivated () {
    this.$off('event:bind-widget')
    this.$off('event:open-gadget')
    this.$off('event:preview-widget')
    this.$root.eventBus.$off('updateTemplateId')
    this.$root.eventBus.$off('closeDialog')
    this.$root.eventBus.$off('gadgetLoadingStatusCheck')
    this.$root.eventBus.$off('event:updateGadgets')
    bus.$off('Dashboards-Share')
  },
  beforeDestroy () {
    this.$off('event:bind-widget')
    this.$off('event:open-gadget')
    this.$off('event:preview-widget')
    this.$root.eventBus.$off('updateTemplateId')
    this.$root.eventBus.$off('closeDialog')
    this.$root.eventBus.$off('gadgetLoadingStatusCheck')
    this.$root.eventBus.$off('event:updateGadgets')
    bus.$off('Dashboards-Share')
  },
  computed: {
 
    GadgetList: {
      get () {
        let tempList = []
        tempList = this.userGadgetList
        return tempList
      },
      set (newVal) {
        this.businessTypeListrecord = newVal
      }
    },
    businessTypeList () {
      return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_type_list').dataList
    },
    hasEditPermission () {
      let reportadmin = this.$hasPermission('sys:report:reportadmin') ? 1 : 0
      let editAuth = this.$hasPermission('sys:report:edit') ? 1 : 0
      let isCustom = this.businessTypeForWidget === 'Custom' ? 1 : 0
      if (reportadmin + editAuth + isCustom >= 2) {
        return true
      } else {
        return false
      }
    },
    gadgets1: {
      set (val) {
        this.gadgets = [...val, ...this.gadgets.slice(1)]
      },
      get () {
        return [this.gadgets[0]]
      }
    },
    gadgets2: {
      set (val) {
        this.gadgets = [this.gadgets[0], ...val]
      },
      get () {
        return this.gadgets.slice(1)
      }
    },
    isShow () {
      return this.gadgets.some(item => item.gadgetType === 'pageheadergadget')
    },
    comPageWidth () {
      return document.querySelector('.vue-grid-layout')?document.querySelector('.vue-grid-layout').clientWidth:window.screen.width-200
    }
  },
  watch: {
    userGadgetList (val) {
      this.businessTypeListrecord = this.filterHasWidget(val)
    },
    businessTypeListrecord (val) {
      this.broadcast('PublishedWidget', 'event:get-published-widgets', { widgets: val })
    },

    '$store.state.bot.routeMeta': function (val) {
      this.getDashboardLayout()
    },
    $route: {
      handler (to, from) {
        try {
            const clonewidget = JSON.parse(localStorage.getItem(`cloneWightToDashboards-${this.pageId}`))
            const clonerefresh = JSON.parse(localStorage.getItem(`clonerefresh`))
            if (clonewidget&&clonewidget.id&&clonerefresh) {
              this.refresh && this.refresh()
              localStorage.removeItem(`clonerefresh`)
            }
            if (to.query.pageid === '1386509689588142081') {
            if (this.$store.state.bot.RealtimeBotsMessageReportforTeamsMessageFotterBotId !== to.query.botId) {
              this.refresh && this.refresh()
              this.$store.state.bot.RealtimeBotsMessageReportforTeamsMessageFotterBotId = to.query.botId
            }
          }
        } catch (error) {

        }
      },
      immediate: true
    }

  },
  methods: {
    // getNextAppInfo () {
    //   return getNextAppInfo('resourceId', 'nextTicketType')
    // },
    isSlicer (val) {
      let obj = dashboardGadgetList.find((item) => {
        return item.key === val
      })
      if (obj && obj.type === 'slicer') {
        return true
      } else {
        return false
      }
    },
    gadgetLoadingStatusCheck () {
      try {
        setTimeout(() => {
          // if (this.$refs['dashboard-page-tag']) this.$refs['dashboard-page-tag'].id = `dashboard-page-tag-${this.pageId}`
        }, 30000)
      } catch (error) { }
    },
    gadgetTypeImgUrl (type) {
      let obj = this._.filter(dashboardGadgetList, { key: type })
      return obj[0].imageUrl || ''
    },
    hasPageHeaderPer (type) {
      let headeradmin = this.$hasPermission('sys:report:pageheaderadmin') ? 1 : 0
      let editadmin = this.$hasPermission('sys:tenant:model:allowtomanage:report:temmodel') ? 1 : 0
      let auth = false
      if (type === 'pageheadergadget') {
        if (headeradmin + editadmin > 1) {
          auth = true
        }
      } else {
        if (editadmin > 0) {
          auth = true
        }
      }
      return auth
    },
    clearFormData () {
      this.currentPage = 1
      this.searchVal = ''
      this.dataForm.dataset = ''
      this.businessTypeListrecord = []
      this.checkedCities = []
    },

    PreviewWidget (item) {
      this.commandClick(item)
    },
    reportMoreEdit () {
      this.visible = false
      this.$emit('editMoreReportShow', true)
    },
    handleCheckedCitiesChange (value) {
      this.checkedGauge = value
    },
    filterHasWidget (value) {
      let tempList = value
      if (this.businessTypeForWidget !== 'MSPbots Internal') {
        if (this.businessTypeForWidget === 'Template') {
          tempList = this._.reject(tempList, { businessType: 'Custom' })
        }
        tempList = this._.reject(tempList, { businessType: 'MSPbots Internal' })
      }
      let arr = []
      let tempListArr = []
      this.gadgets.forEach(element => {
        arr.push(element.i)
      })
      tempList.forEach(element => {
        if (arr.indexOf(element.gadgetId) === -1) {
          tempListArr.push(element)
        }
      })
      return tempListArr
    },
    checkedName (val) {
      this.currentPage = 1
      if (this.businessTypeForWidget === 'Template') {
        this.GadgetList = this.filterHasWidget(this.userGadgetList).filter(e => e.businessType === 'Template').filter(e => e.name.toLowerCase().indexOf(val.toLowerCase()) !== -1)
      } else {
        this.GadgetList = this.filterHasWidget(this.userGadgetList).filter(e => e.name.toLowerCase().indexOf(val.toLowerCase()) !== -1)
      }
    },
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage
    },
    showDesign () {
      this.showMsg = !this.showMsg
    },
    closeDesign () {
      this.showMsg = false
      this.editMode = false
    },

    bindWidget ({ widgets }) {
      this.checkedGauge = widgets.map(({ gadgetId }) => gadgetId)

      this.addGadgetToPageGroup()

      this.broadcast('PublishedWidget', 'event:clear-widgets')
    },
    addGadgetToPageGroup () {
      this.filterHasWidget(this.userGadgetList).forEach(ele => {
        if (this.checkedGauge.includes(ele.gadgetId)) {
          this.reportRelationIntrogrationList.concat(ele.integrationCode)
          this.addGadgetToPage(ele)
          this.dialog = false
        }
      })
      this.checkedGauge = []
    },
    checkeConnectNextTicket (codeList) {
      for (const key in codeList) {
        if (Object.hasOwnProperty.call(codeList, key)) {
          const element = codeList[key]
          if (this.reportIntegrationCode[0] === 'AUTOTASK' && this.reportIntegrationCode.includes(key) && element.sync.group !== 1) {
            this.nextTicketFrom = 'AUTOTASK'
            this.$refs.nextTicketConnectTipDialog.visible = true
            break
          } else if (this.reportIntegrationCode[0] === 'CW' && this.reportIntegrationCode.includes(key) && element.sync.group !== 1) {
            this.nextTicketFrom = 'CW'
            this.$refs.nextTicketConnectTipDialog.visible = true
          }
        }
      }
    },
    getIntegrationList (businessId) {
      var _self = this
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      return this.$interface.taskManager.getConnectorInfoNew(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (businessId === '1357516578732232706' || businessId === '1357516578732232707') {
            this.checkeConnectNextTicket(res.data)
          } else {
            if (!(_self.gadgets.length === 1 && _self.gadgets[0].com === 'pageheadergadget')) {
              for (const key in res.data) {
                if (Object.hasOwnProperty.call(res.data, key)) {
                  const element = res.data[key]
                  if (_self.reportIntegrationCode.length > 0 && _self.reportIntegrationCode.includes(key) && (element.sync.group === 2 || element.sync.group === 3) && _self.businessTypeForWidget !== 'MSPbots Internal') {
                    _self.$refs['inter-get-started-dialog'].visible = true
                    break
                  }
                }
              }
            }
          }
        }).catch(() => {
        })
    },
    commandClick (row) {
      this.queryModelDefaultSetting.dataInfo = {
        ...row
      }

      this.$nextTick(() => {
        this.$store.state.isWidget = true
        this.showQueryModel()
      })
    },
    getGadgetSetting (key) {
      return defaultGadgetSettingList.find(e => e.gadgetType === key).gadgetSetting || {}
    },
    selectGadget (record) {
      const { key } = record
      const widget = {
        businessId: '',
        gadgetId: getUUID(),
        gadgetType: key,
        gadgetSetting: this.getGadgetSetting(key),
        reuse: true,
        datasetSetting: {}
      }

      this.showWidgetDesign(widget)
    },
    showWidgetDesign (row) {
      this.queryModelDefaultSetting.dataInfo.datasetSetting = {}
      this.queryModelDefaultSetting.dataInfo = Object.assign(this._.merge(this.queryModelDefaultSetting.dataInfo, row))
      this.queryModelDefaultSetting.showMoreEditSetting = true
      this.$nextTick(() => {
        this.$store.state.isWidget = true
        this.showQueryModel()
      })
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    async queryModelClosed () {
      this.$set(this.queryModelDefaultSetting, 'showSetting', false)
      const [item] = this.widgets
      if (item) {
        const row = getGadget(item)
        const index = this.gadgets.findIndex(record => record.id === row.id)
        if (index !== -1) {
          this.gadgets.splice(index, 1, row)
        } else {
          this.gadgets = this.gadgets.slice(0,1).concat(row,this.gadgets.slice(1)).filter(item=>item.id||item.com==='pageheadergadget')
        }
      }
      this.gadgetChoiceModalVisible = false
      this.query()
    },

    async refreshDataList (widget) {
      this.widgets = [widget]
    },

    updateGadget () {

    },
    mappingForm (to, from) {

    }
  },
  beforeCreate () {
    this.$options.components.InterGetStarted = () => import('./intergrations-get-started/index')
  }
}
</script>
<style lang="scss" scoped>
// ::v-deep .el-dialog .el-dialog__body {
//   flex: 1;
//   overflow: auto;
// }
// ::v-deep .el-dialog {
//   display: flex;
//   flex-direction: column;
//   margin: 0 !important;
//   position: absolute;
//   top: 50%;
//   left: 50%;
//   transform: translate(-50%, -50%);
//   height: 90vh;
// }
::v-deep .e-popup {
  top: 0 !important;
}
::v-deep .e-dlg-content {
  // max-height: 100px;
}
</style>
<style lang="scss">
.report_layout {
  ::v-deep .select_widget_filter_condition {
    background: url("../../../../assets/select_widget-filter-icon.png");
    background-repeat: no-repeat;
    background-position: center left;
    background-size: 14px 14px;
    padding-left: 20px;
    .filter_condition_lf {
      .filter_condition {
        margin-top: 8px;
        margin-left: 5px;
      }
    }
    .filter_condition_lf > div {
      float: left;
      width: 150px;
      margin-right: 10px;
    }
    .filter_condition_lf > div:nth-child(1) {
      width: auto;
    }
  }
  // .vue-grid-layout {
  //   height: auto !important;
  // }
  // .vue-grid-item {
  //   height: auto !important;
  // }
  .auto_class {
    height: auto !important;
  }
  .select_widget_filter_condition::after {
    content: ".";
    clear: both;
    display: block;
    overflow: hidden;
    height: 0;
  }
  .widget_data_list {
    margin-top: 20px;
    min-height: 20px;
    .el-checkbox-group {
      > .is-checked {
        border: 1px solid #138dc7;
        .el-checkbox__inner {
          // background-image: url('../../../../assets/add_reports_radio_selected.png');
          // background-repeat: no-repeat;
          // background-position: center;
          // background-size: 14px 14px;
        }
        .el-checkbox__inner::after {
          // transform: rotate(0deg) scaleY(0);
        }
      }
      .el-checkbox__inner {
        // border: 0;
        // background-image: url('../../../../assets/add_reports_radio.png');
        // background-repeat: no-repeat;
        // background-position: center;
        // background-size: 14px 14px;
        // background-color: transparent;
      }
    }
    .el-checkted {
      // border: 1px solid #138DC7 !important;
    }
    .el-checkbox {
      display: block;
      margin-right: 0;
      background: #ffffff;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      margin-top: 10px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .el-checkbox__input {
        display: block;
        width: 54px;
        text-align: center;
      }
      .el-checkbox__label {
        flex: 1;
        display: block;
        height: 100%;
        padding-left: 0;
        .item_widget {
          // background: url('../../../../assets/grid.png');
          background-size: 48px 48px;
          background-repeat: no-repeat;
          background-position: left center;
          height: 100%;
          // padding-left: 54px;
          padding-top: 5px;
          padding-bottom: 5px;
          display: flex;
          justify-content: space-around;
          align-items: center;
          min-height: 70px;
          .item_widget_content {
            flex: 1;
            height: 100%;
            padding-right: 10px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            > div {
              white-space: pre-wrap;
              word-break: break-word;
            }

            > div:nth-child(1) {
              color: #000;
              font-size: 14px;
            }
            > div:nth-child(2) {
              font-size: 14px;
              color: rgba(0, 0, 0, 0.49);
            }
          }
          .item_widget_ri {
            float: right;
            width: 53px;
            height: 100%;
            text-align: center;
            .item {
              height: 14px;
              width: 14px;
              border: 0;
              background: url("../../../../assets/select_widget_eye.png");
              background-size: 14px 14px;
              background-repeat: no-repeat;
              background-position: center;
            }

            // box-shadow: -1px 0px 0px 0px #F0F0F0;
            // margin: 5px 0;
          }
          position: relative;
        }
        .item_widget::after {
          content: "";
          clear: both;
          display: block;
          overflow: hidden;
          // height: 0;
          position: absolute;
          right: 53px;
          border-right: 1px solid #f0f0f0;
          height: 80%;
        }
      }
    }
    .el-checkbox::after {
      content: ".";
      clear: both;
      display: block;
      overflow: hidden;
      height: 0;
    }
  }
  .el-pagination {
    text-align: center;
  }
  .layoutTitle {
    font-size: 12px;
    word-break: keep-all;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .layoutTitle:hover {
    overflow: visible;
  }

  .vue-grid-item.vue-grid-placeholder {
    background: #f2f8ff;
    border: 1px solid #38f;
    opacity: 1;
  }

  .layoutJSON {
    background: #ddd;
    border: 1px solid black;
    margin-top: 10px;
    padding: 10px;
  }

  .eventsJSON {
    background: #ddd;
    border: 1px solid black;
    margin-top: 10px;
    padding: 10px;
    height: 100px;
    overflow-y: scroll;
  }

  .columns {
    -moz-columns: 120px;
    -webkit-columns: 120px;
    columns: 120px;
  }

  .vue-resizable-handle {
    z-index: 5000;
    position: absolute;
    width: 20px;
    height: 20px;
    bottom: 0;
    right: 0;
    background: url("");
    background-position: bottom right;
    padding: 0 3px 3px 0;
    background-repeat: no-repeat;
    background-origin: content-box;
    box-sizing: border-box;
    cursor: se-resize;
  }

  .editmode:not(.vue-grid-placeholder) {
    border: 1px solid #38f;
    opacity: 0.5;
  }

  .vue-grid-item.resizing {
    opacity: 0.9;
  }

  .vue-grid-item .no-drag {
    height: 100%;
    width: 100%;
  }

  .vue-grid-item .minMax {
    font-size: 12px;
  }

  .vue-grid-item .add {
    cursor: pointer;
  }

  .vue-draggable-handle {
    position: absolute;
    width: 20px;
    height: 20px;
    top: 0;
    left: 0;
    background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><circle cx='5' cy='5' r='5' fill='#999999'/></svg>")
      no-repeat;
    background-position: bottom right;
    padding: 0 8px 8px 0;
    background-repeat: no-repeat;
    background-origin: content-box;
    box-sizing: border-box;
    cursor: pointer;
  }

  .layout-item {
    text-align: center;
    margin-bottom: 15px;
    padding: 0 5px;
  }

  .layout-item .bottom {
    position: relative;
    margin-top: 15px;
  }

  .layout-item .bottom span {
    display: block;
    float: left;
    width: 50%;
    margin-top: 12px;
    text-align: left;
  }

  .layout-item .bottom button {
    padding-top: 0;
  }

  .top-toolbar {
    position: relative;
    margin-top: -15px;
    height: 35px;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    background-color: #fff;
    margin-left: -15px;
    padding-top: 10px;
    width: calc(100% + 30px);
  }

  .top-toolbar .top-toolbar-title {
    padding-left: 25px;
  }

  .btnBox {
    height: 16px;
    padding: 0px 10px;
    background: #c4ebf3;
    position: absolute;
    top: -15px;
    right: 24px;
    border-bottom-left-radius: 6px;
    border-bottom-right-radius: 6px;
  }

  .showBtn {
    font-size: 18px;
    color: #00c4ed;
  }

  .closeBtn {
    font-size: 18px;
    position: absolute;
    top: 8px;
    right: 11px;
  }
  .widget_div_item {
    visibility: hidden;
  }
  .widget_div:hover .widget_div_item {
    visibility: visible;
  }
  .widget_div_item:hover {
    visibility: visible;
  }
  .widget_div:hover .more_menu_box {
    display: block;
  }
  .widget_div:hover span.el-icon-more {
    display: block;
  }
}
.fullScreenDialog {
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  z-index: 1999;
  background: #fff;
}
// .blueTheme{
//   width: 50%;
//   height: 300px;
//   position: absolute;
//   bottom: 15px;
//   left: 50%;
//   transform: translateX(-50%);
// }
// .blueTheme::after{
//     content: "";
//     position: absolute;
//     background: rgb(0, 2, 18);
//     width: 200%;
//     left: -50%;
//     aspect-ratio: 1 / 0.7;
//     border-radius: 50%;
//     border-top: 1px solid rgba(120, 119, 198, 0.4);
//     top: 50%;
//     color: #7877C6;
// }
// .blueTheme::before{
//     content: "";
//     position: absolute;
//     inset: 0px;
//     background: radial-gradient(circle at bottom center,#7877C6,transparent 70%);
//     opacity: 0.4;
//     color: #7877C6;
// }
</style>
